{% extends 'html/all.html' %}
{% block title %}
    商品详情
{% endblock %}
{% block content %}
    <style>
        :root {
            --primary-color: #333;
            --secondary-color: #777;
            --accent-color: #f9a825;
        }

        .product-details {
            display: grid;
            grid-template-columns: 1fr 2fr;
            gap: 20px;
            align-items: start;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        .product-details h1, h2, h3, h4, p {
            color: var(--primary-color);
        }

        .product-details img {
            max-width: 100%;
            height: auto;
            object-fit: cover;
            transition: transform 0.3s ease-in-out;
        }

        .product-details img:hover {
            transform: scale(1.05);
        }

        .product-images {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 10px;
        }

        .product-details h1 span,
        .product-details h2 span,
        .product-details h3 span,
        .product-details h4 span,
        .product-details p span {
            color: var(--secondary-color);
        }

        .product-details h1 span {
            color: var(--accent-color);
        }

        /* Add these lines to set a fixed size for the carousel items */
        .carousel-item {
            width: 600px; /* Adjust as needed */
            height: 400px; /* Adjust as needed */
        }
        .carousel-control-prev-icon,
        .carousel-control-next-icon {
            height: 50px;
            width: 50px;
            background-color: bisque;
            background-size: 50px 50px;
        }
    </style>
    <div class="product-details">
        <h1>商品ID: <span id="product_id">{{ product_id }}</span></h1>
        <h2>商品名称: <span id="product_name"></span></h2>
        <h3>商品所属人: <span id="username"></span></h3>
        <h4>商品价格: <span id="price"></span>￥</h4>
        <div id="productCarousel" class="carousel slide" data-bs-ride="carousel" data-bs-interval="10000">

            <div class="carousel-inner">

                <div class="carousel-item active" id="carousel_item_url" style="display: none;">
                    <a href="" data-lightbox="product-images" id="image_url_link">
                        <img id="image_url" src="" class="d-block w-100" alt="商品图片">
                    </a>
                </div>
                <div class="carousel-item" id="carousel_item_two" style="display: none;">
                    <a href="" data-lightbox="product-images" id="image_two_link">
                        <img id="image_two" src="" class="d-block w-100" alt="">
                    </a>
                </div>
                <div class="carousel-item" id="carousel_item_three" style="display: none;">
                    <a href="" data-lightbox="product-images" id="image_three_link">
                        <img id="image_three" src="" class="d-block w-100" alt="">
                    </a>
                </div>
                <div class="carousel-item" id="carousel_item_four" style="display: none;">
                    <a href="" data-lightbox="product-images" id="image_four_link">
                        <img id="image_four" src="" class="d-block w-100" alt="">
                    </a>
                </div>
                <div class="carousel-item" id="carousel_item_five" style="display: none;">
                    <a href="" data-lightbox="product-images" id="image_five_link">
                        <img id="image_five" src="" class="d-block w-100" alt="">
                    </a>
                </div>
                <div class="carousel-item" id="carousel_item_six" style="display: none;">
                    <a href="" data-lightbox="product-images" id="image_six_link">
                        <img id="image_six" src="" class="d-block w-100" alt="">
                    </a>
                </div>
                <!-- 添加更多图片... -->
            </div>
            <button class="carousel-control-prev" type="button" data-bs-target="#productCarousel" data-bs-slide="prev">
                <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                <span class="visually-hidden">上一张</span>
            </button>
            <button class="carousel-control-next" type="button" data-bs-target="#productCarousel" data-bs-slide="next">
                <span class="carousel-control-next-icon" aria-hidden="true"></span>
                <span class="visually-hidden">下一张</span>
            </button>
        </div>
        <p>商品描述: <span id="description"></span></p>
        <p>商品状态: <span id="condition"></span></p>
        <p>发布日期: <span id="posted_date"></span></p>
        <p>卖家信用分: <span id="credits"></span></p>
        <button id="contactSellerButton" class="btn btn-primary">联系卖家</button>
        <button id="buyButton" class="btn btn-success">预订商品（请联系卖家购买）</button>
        <button id="addToCartButton" class="btn btn-warning">加入购物车</button>
        <button id="addToFavoritesButton" class="btn btn-info">收藏</button>
    </div>
        <script src="/static/js/check_token.js"></script>

    <link href="https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.3/css/lightbox.min.css" rel="stylesheet">
{% endblock %}
{% block scripts %}
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
   $('#buyButton').click(function () {
    var product_id = "{{ product_id }}";
    var username = localStorage.getItem('username');
    var buttonText = $(this).text();

    if (buttonText === '预订商品（请联系卖家购买）') {
        $.ajax({
    url: '/api/buy',
    type: 'POST',
    data: {
        username: username,
        id: product_id
    },
    success: function (response) {
        if (response.status === 'success') {
            alert('预订成功');
            location.reload();
        } else {
            alert(response.msg);  // 显示服务器返回的错误消息
                        location.reload();

        }
    },
    error: function (xhr, status, error) {
        console.error('AJAX 请求失败:', error);
    }
});
    } else if (buttonText === '取消预订') {
        $.ajax({
            url: '/api/delete_buy',
            type: 'POST',
            data: {
                username: username,
                id: product_id
            },
            success: function (response) {
                if (response.status === 'success') {
                    alert('取消预订成功');
                    location.reload();
                } else {
                    console.error('取消预订失败:', response.message);
                }
            },
            error: function (xhr, status, error) {
                console.error('AJAX 请求失败:', error);
            }
        });
    }
});
    $(document).ready(function () {
    var product_id = "{{ product_id }}";
    var username = localStorage.getItem('username');
    $.ajax({
        url: '/api/check_buy',
        type: 'POST',
        data: {
            username: username,
            id: product_id
        },
        success: function (response) {
            if (response.msg === '已被预订') {
                $('#buyButton').text('已被预订');
                $('#buyButton').prop('disabled', true);
            } else if (response.msg === '可以取消预订') {
                $('#buyButton').text('取消预订');
            } else {
                $('#buyButton').text('预订商品（请联系卖家购买）');
            }
        },
        error: function (xhr, status, error) {
            console.error('AJAX 请求失败:', error);
        }
    });
});
        $(document).ready(function () {
            var product_id = "{{ product_id }}";
            $.ajax({
                url: '/api/show_details',
                type: 'GET',
                data: {
                    id: product_id
                },
                success: function (response) {
                    if (response.status === 'success') {
                        console.log('加载商品详情成功:', response.data);
                        var data = response.data;
                        $('#product_name').text(data.ProductName);
                        $('#username').text(data.username);
                        $('#price').text(data.Price);
                        $('#description').text(data.Description);
                        $('#condition').text(data.Condition);
                        $('#posted_date').text(data.PostedDate);
                        $('#credits').text(data.Credits);
// 获取 localStorage 中的 username
                var localStorageUsername = localStorage.getItem('username');
                // 如果商品所属人的 username 与 localStorage 中的 username 相同
                if (localStorageUsername === data.username) {
                    // 隐藏按钮
                    $('#contactSellerButton').hide();
                    $('#buyButton').hide();
                    $('#addToCartButton').hide();
                    $('#addToFavoritesButton').hide();
                }
                        // Create an array to store all the image data
                        var images = [
                            {id: 'image_url', link: 'image_url_link', item: 'carousel_item_url', url: data.ImageURL},
                            {id: 'image_two', link: 'image_two_link', item: 'carousel_item_two', url: data.image_two},
                            {
                                id: 'image_three',
                                link: 'image_three_link',
                                item: 'carousel_item_three',
                                url: data.image_three
                            },
                            {
                                id: 'image_four',
                                link: 'image_four_link',
                                item: 'carousel_item_four',
                                url: data.image_four
                            },
                            {
                                id: 'image_five',
                                link: 'image_five_link',
                                item: 'carousel_item_five',
                                url: data.image_five
                            },
                            {id: 'image_six', link: 'image_six_link', item: 'carousel_item_six', url: data.image_six}
                        ];

                        // Clear the carousel inner
                        $('.carousel-inner').empty();

                        // Iterate over the images array to create carousel items
                        images.forEach(function (image, index) {
                            if (image.url) {
                                var activeClass = index === 0 ? ' active' : '';
                                $('.carousel-inner').append(
                                    `<div class="carousel-item${activeClass}" id="${image.item}">
                                <a href="#" id="${image.link}">
                                    <img id="${image.id}" src="${image.url}" class="d-block w-100" alt="">
                                </a>
                            </div>`
                                );
                                // Add click event listener to open image in new window
                                $(`#${image.link}`).click(function(event) {
                                    event.preventDefault();
                                    window.open(image.url, '_blank');
                                });
                            }
                        });
                    } else {
                        console.error('加载商品详情失败:', response.message);
                    }
                },
                error: function (xhr, status, error) {
                    console.error('AJAX 请求失败:', error);
                }
            });
            // Add click event listener for 'contactSellerButton'
            $('#contactSellerButton').click(function () {
                // 获取当前登录用户的username
                 var currentUser = localStorage.getItem('username');
                // 获取商品所属人的username
                var sellerUser = $('#username').text();
                // 将这两个username作为参数添加到URL中，并跳转到/chat页面
                window.location.href = '/chat?&请复制等号后面商品所属人=' + sellerUser;
            });

            var product_id = "{{ product_id }}";
            var username = localStorage.getItem('username');
            $.ajax({
            url: '/api/get_collection',
            type: 'GET',
            data: {
                username: username,
                id: product_id
            },
            success: function (response) {
                if (response.status === 'success') {
                    $('#addToFavoritesButton').text('取消收藏');
                } else {
                    $('#addToFavoritesButton').text('收藏');
                }
            },
            error: function (xhr, status, error) {
                console.error('AJAX 请求失败:', error);
            }
        });
        $('#addToFavoritesButton').click(function () {
        var button = $(this);
        var buttonText = button.text();
        if (buttonText === '取消收藏') {
            var product_id = "{{ product_id }}";
            var username = localStorage.getItem('username');
            $.ajax({
                url: '/api/delete_collection',
                type: 'POST',
                data: {
                    username: username,
                    id: product_id
                },
                success: function (response) {
                    if (response.status === 'success') {
                        alert('取消收藏成功');
                        button.text('收藏');
                    } else {
                        console.error('取消收藏失败:', response.message);
                    }
                },
                error: function (xhr, status, error) {
                    console.error('AJAX 请求失败:', error);
                }
            });
        } else if (buttonText === '收藏') {
            var product_id = "{{ product_id }}";
            var username = localStorage.getItem('username');
            $.ajax({
                url: '/api/collection',
                type: 'POST',
                data: {
                    username: username,
                    id: product_id
                },
                success: function (response) {
                    if (response.status === 'success') {
                        alert('收藏成功');
                                            button.text('取消收藏');

                    } else {
                        console.error('收藏失败:', response.message);
                    }
                },
                error: function (xhr, status, error) {
                    console.error('AJAX 请求失败:', error);
                }
            });
        }
    });




    var product_id = "{{ product_id }}";
    var username = localStorage.getItem('username');
    $.ajax({
        url: '/api/get_cart',
        type: 'GET',
        data: {
            username: username,
            id: product_id
        },
        success: function (response) {
            if (response.status === 'success') {
                $('#addToCartButton').text('取消加入购物车');
            } else {
                $('#addToCartButton').text('加入购物车');
            }
        },
        error: function (xhr, status, error) {
            console.error('AJAX 请求失败:', error);
        }
    });
    $('#addToCartButton').click(function () {
    var button = $(this);
    var buttonText = button.text();
    if (buttonText === '取消加入购物车') {
        var product_id = "{{ product_id }}";
        var username = localStorage.getItem('username');
        $.ajax({
            url: '/api/delete_cart',
            type: 'POST',
            data: {
                username: username,
                id: product_id
            },
            success: function (response) {
                if (response.status === 'success') {
                    alert('取消加入购物车');
                    button.text('加入购物车');
                } else {
                    console.error('取消加入购物车失败:', response.message);
                }
            },
            error: function (xhr, status, error) {
                console.error('AJAX 请求失败:', error);
            }
        });
    } else if (buttonText === '加入购物车') {
        var product_id = "{{ product_id }}";
        var username = localStorage.getItem('username');
        $.ajax({
            url: '/api/cart',
            type: 'POST',
            data: {
                username: username,
                id: product_id
            },
            success: function (response) {
                if (response.status === 'success') {
                    alert('加入购物车成功');
                                        button.text('取消加入购物车');

                } else {
                    console.error('加入购物车失败:', response.message);
                }
            },
            error: function (xhr, status, error) {
                console.error('AJAX 请求失败:', error);
            }
        });
    }
});
        });
    </script>
{% endblock %}